<script>
import * as DateUtil from '@/components/util/DateUtil'
import * as IncreaseUtil from '@/components/util/IncreaseUtil'
export default {
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  data() {
    return {
      energyInfo: {
        data: []
      },
      energyCompareChartInfo: {
        option: {
          tooltip: {
            trigger: 'item',
            formatter: function (c) {
              let unite = c.seriesName
              return '项目：' + c.data.name + '<br>能耗：' + c.data.value + ' ' + unite + '<br>占比：' + c.percent + '%';
            }
          },
          series: [{type: 'pie',data: []}]
        }
      },
      onlineViewInfo: {
        option: {
          grid: {left: '2%',right: '2%',bottom: '2%',containLabel: true},
          tooltip: {
            trigger: 'axis',
            formatter: function (c) {
              return '时间：' + c[0].name + '<br>能耗：' + c[0].value + ' ' + c[0].seriesName;
            }
          },
          xAxis: {type: 'category',data: []},
          yAxis: {type: 'value'},
          series: [{  type: 'line',  data: []}
          ]
        }
      },
      filterText: '',
      increaseStandValue: '',
      increaseCashValue: '',
      standUit: '',
      cashUnit: '',
      subjectInfo: {
        dialogVisible: false,
        selected: {
          label: '请选择院所/建筑/科室'
        },
        treeData: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        }
      },
      datePickInfo: {
        selected: [new Date(new Date().getTime() - 1000 * 60 * 60 * 24 * 7), new Date()],
        option: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      meterInfo: {
        data: [],
        selected: {}
      },
      pointInfo: {
        dialogVisible: false,
        hasOpen: false,
        data: [],
        option:{
          grid: {left: '2%',right: '2%',bottom: '2%',containLabel: true},
          tooltip: {trigger: 'axis'},
          xAxis: {type: 'category',data: []},
          yAxis: {type: 'value'},
          series: [{  type: 'line',  data: []}
          ]
        }
      }
    };
  },
  mounted() {
    this.fetchBaseData()
  },
  methods: {
    fetchData: function () {
      if (!this.subjectInfo.selected.id || !this.subjectInfo.selected.type) {
        this.$message("请选择院所/建筑/科室")
        return
      }
      const subjectId = this.subjectInfo.selected.id
      const subjectType = this.subjectInfo.selected.type
      this.fetchMeterData(subjectId, subjectType)
      this.onlineViewInfoChart(subjectId, subjectType, this.$refs.subjectOnlineView, this.onlineViewInfo.option, 'increaseStandValue', list => {
        this.increaseStandValue = IncreaseUtil.doubleLab(IncreaseUtil.sumValue(list, 'increaseStandValue'));
        this.increaseCashValue = IncreaseUtil.doubleLab(IncreaseUtil.sumValue(list, 'increaseCashValue'));
      })
      this.compareChart(subjectId, subjectType)
    },
    fetchMeterData: function (subjectId, subjectType) {
      const data = {
        content: {
          subjectId: subjectId,
          subjectType: subjectType
        }
      }
      this.$axios({url:'/ems/client/base/meter/list',data: data}).then((content) => {
        this.meterInfo.data = content.list
        if (content.list && content.list.length > 0) {
          this.meterInfo.selected = content.list[0]
        }else {
          this.meterInfo.selected = {}
        }
      });
    },
    compareChart: function (subjectId, subjectType) {
      const data = {
        content: {
          subjectId: subjectId,
          subjectType: subjectType,
          fromDate: this.$getTimeInfo(this.datePickInfo.selected[0]).toDay + ' 00:00:00',
          toDate: this.$getTimeInfo(this.datePickInfo.selected[1]).toDay + ' 23:59:59'
        }
      }
      let option = this.energyCompareChartInfo.option;
      let url = '/ems/client/index/energy/compare';
      let ref = this.$refs.energyCompare;
      option.series[0].name = this.standUit
      this.$axios({url: url, data: data}).then((content) => {
        const list = content.list
        option.series[0].data = []
        for (let i = 0; i < list.length; i ++) {
          const item = list[i]
          option.series[0].data.push({name: item.name, value: this.$doubleVal(item.increaseStandValue)});
        }
        this.$nextTick(() => {
          const chart = this.$echarts.init(ref)
          chart.setOption(option)
        })
      })
    },
    onlineViewInfoChart: function (subjectId, subjectType, ref, option, field, func) {
      const data = {
        content: {
          subjectId: subjectId,
          subjectType: subjectType,
          fromDate: this.$getTimeInfo(this.datePickInfo.selected[0]).toDay + ' 00:00:00',
          toDate: this.$getTimeInfo(this.datePickInfo.selected[1]).toDay + ' 23:59:59',
          toDateType: DateUtil.getToDate(this.datePickInfo.selected[0], this.datePickInfo.selected[1])
        }
      }
      option.series[0].name = this.standUit
      this.$axios({url:'/ems/client/index/energy/time/trend', data: data}).then((content) => {
        const list = content.list
        if (func) {
          func(list)
        }
        option.xAxis.data = [];
        option.series[0].data = [];
        for (let i = 0; i < list.length; i ++) {
          const item = list[i]
          option.xAxis.data.push(item.time);
          option.series[0].data.push(this.$doubleVal(item['' + field + '']));
        }
        this.$nextTick(() => {
          const chart = this.$echarts.init(ref)
          chart.setOption(option)
        })
      })
    },
    fetchBaseData: function () {
      const data = {content: {excludeTypes:["DIAGRAM", "METER", "POINT", "GATEWAY"]}}
      this.$axios({url:'/ems/client/energy/search/subject/tree',data: data}).then((content) => {
        this.subjectInfo.treeData = content.list
        if (content.list && content.list.length > 0) {
          this.subjectInfo.selected = content.list[0]
          this.$axios({url:'/ems/client/index/energy/list',data: {content: {}}}).then((content) => {
            this.cashUnit = content.cashUnite
            this.standUit = content.standUnite
            this.energyInfo.data = content.list
            this.fetchData()
          });
        }else {
          this.subjectInfo.selected = {}
        }
      });
    },
    treeClick: function (item) {
      this.subjectInfo.dialogVisible = false
      this.subjectInfo.selected = item
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleClick(tab) {
      const meter = JSON.parse(tab.name)
      const param = {content: {meterId: meter.id } }
      this.$axios({url:'/ems/client/base/point/list',data: param}).then((content) => {
        this.pointInfo.data = content.list
      })
    },
    tableRowClassName({rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    tableItemDetail: function (point) {
      let field = 'increaseStandValue'
      if (point.dataType === 'PROCESS') {
        field = 'increaseRealValue'
      }
      this.pointInfo.dialogVisible = true
      this.onlineViewInfoChart(point.id, 'POINT', this.$refs.pointOnlineView, this.pointInfo.option, field)
      if (!this.pointInfo.hasOpen) {
        this.pointInfo.hasOpen = true
        setTimeout(() => {
          this.onlineViewInfoChart(point.id, 'POINT', this.$refs.pointOnlineView, this.pointInfo.option, field)
        }, 2000)
      }
    }
  }
};
</script>

<template>
<div>
  <el-row>
    <el-col :span="24" style="height: 50px;">
      <el-button type="text" @click="subjectInfo.dialogVisible = true" style="background-color: white;width: 350px;color: rgb(192, 196, 204);">{{subjectInfo.selected.label}}</el-button>
      <el-dialog :visible.sync="subjectInfo.dialogVisible" width="30%">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText">
        </el-input>
        <el-tree class="filter-tree" :data="subjectInfo.treeData" :props="subjectInfo.defaultProps" :filter-node-method="filterNode" @node-click="treeClick" ref="tree"> </el-tree>
      </el-dialog>
      &nbsp;
      <el-date-picker v-model="datePickInfo.selected" type="daterange" align="right" unlink-panels range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :picker-options="datePickInfo.option"> </el-date-picker>
      &nbsp;
      <el-button @click="fetchData">查询</el-button>
    </el-col>
  </el-row>
  <el-row style="margin-top: 1%;">
    <el-col :span="24">
      <el-descriptions title="综合能耗概览" border>
        <el-descriptions-item label="综合耗能（标准煤）" labelStyle="width:150px;" span="12">{{ increaseStandValue }} {{standUit}}</el-descriptions-item>
        <el-descriptions-item label="综合耗能（货币）">{{ increaseCashValue }} {{cashUnit}}</el-descriptions-item>
      </el-descriptions>
      <el-row style="margin-top: 1%;">
        <el-col :span="16">
          <el-tabs type="border-card">
            <el-tab-pane label="实时能耗概览">
              <div ref="subjectOnlineView" style="height: 300px;"></div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="8">
          <el-tabs type="border-card">
            <el-tab-pane label="分类对比">
              <div ref="energyCompare" style="height: 300px;"></div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
  <el-row>
    <el-col :span="24" style="margin-top: 1%;">
      <el-descriptions title="仪表信息"></el-descriptions>
      <el-tabs type="border-card" @tab-click="handleClick">
        <el-tab-pane v-for="item in meterInfo.data" :key="item.id" :label="item.name" :name="JSON.stringify(item)">
          <el-row>
            <el-col :span="24" style="line-height: 60px;">
              <el-descriptions title="" border>
                <el-descriptions-item label="所属建筑">{{item.buildingName}}</el-descriptions-item>
                <el-descriptions-item label="仪表ID">{{item.id}}</el-descriptions-item>
                <el-descriptions-item label="仪表编码">{{item.code}}</el-descriptions-item>
                <el-descriptions-item label="能耗类型">
                  <el-tag size="small">{{item.energyName}}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="分项名称">{{item.itemName}}</el-descriptions-item>
                <el-descriptions-item label="一分项名称">{{item.itemOneName}}</el-descriptions-item>
                <el-descriptions-item label="二分项名称">{{item.itemTwoName}}</el-descriptions-item>
              </el-descriptions>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24" style="margin-top: 10px;">
              <el-descriptions title="采集点信息"></el-descriptions>
              <el-table border :data="pointInfo.data" style="width: 100%" :row-class-name="tableRowClassName">
                <el-table-column prop="name" label="名称" width="180"></el-table-column>
                <el-table-column prop="functionName" label="采集参数名称" width="180"></el-table-column>
                <el-table-column prop="gatewayName" label="关联采集器"></el-table-column>
                <el-table-column prop="code" label="采集点编码"></el-table-column>
                <el-table-column prop="dataTypeDesc" label="采集数据类型"></el-table-column>
                <el-table-column prop="lastUploadTime" label="最近一次采集时间"></el-table-column>
                <el-table-column prop="lastUploadRealValueStr" label="最近一次采集值"></el-table-column>
                <el-table-column prop="healthDesc" label="健康状态">
                  <template scope="scope">
                    <i :style="!scope.row.health?'color:red':''" style="font-style: normal;">{{scope.row.healthDesc}}</i>
                  </template>
                </el-table-column>
                <el-table-column prop="stateDesc" label="状态"></el-table-column>
                <el-table-column
                    fixed="right"
                    label="操作"
                    width="100">
                  <template slot-scope="scope">
                    <el-button @click="tableItemDetail(scope.row)" type="text" size="small">查看趋势</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </el-col>
  </el-row>
  <el-dialog
      :visible.sync="pointInfo.dialogVisible"
      width="70%">
    <div ref="pointOnlineView" style="height: 300px;"></div>
  </el-dialog>
</div>
</template>
<style>
.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}
</style>
